<template>
  <div class="device-app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h3>测试执行</h3>
    </div>

    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="left-section">
        <h3>设备列表</h3>
        <div class="device-summary">
          <span class="summary-text">
            已选择 {{ selectedDevices.length }} 台设备
          </span>
        </div>
      </div>

      <div class="right-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设备..."
          clearable
          class="search-input"
          @input="handleDeviceSearch"
        >
          <template #prefix>
            <SvgIcon name="search" size="16px" />
          </template>
        </el-input>

        <el-button-group class="filter-buttons">
          <el-button
            :type="deviceFilter === 'all' ? 'primary' : 'default'"
            size="default"
            @click="setDeviceFilter('all')"
            plain
          >
            全部
          </el-button>
          <el-button
            :type="deviceFilter === 'available' ? 'success' : 'default'"
            size="default"
            @click="setDeviceFilter('available')"
          >
            空闲
          </el-button>
          <el-button
            :type="deviceFilter === 'busy' ? 'warning' : 'default'"
            size="default"
            @click="setDeviceFilter('busy')"
          >
            忙碌
          </el-button>
        </el-button-group>

        <el-button type="primary" size="default" @click="refreshDevices" plain>
          <SvgIcon name="reload" size="18px" />
          <span style="margin-left: 6px">刷新</span>
        </el-button>
      </div>
    </div>

    <!-- 设备统计信息 -->
    <div class="device-stats">
      <span class="stat-item">
        空闲:
        <span class="stat-number idle">{{ availableCount }}</span>
      </span>
      <span class="stat-item">
        忙碌:
        <span class="stat-number busy">{{ busyCount }}</span>
      </span>
      <span class="stat-item">
        总数:
        <span class="stat-number total">{{ availableDevices.length }}</span>
      </span>
    </div>

    <!-- 设备列表 -->
    <div class="device-grid" v-loading="devicesLoading">
      <el-tooltip
        v-for="device in filteredDevices"
        :key="device.device_id"
        :content="getDeviceTooltipContent(device)"
        placement="top"
        :disabled="!shouldShowDeviceTooltip(device)"
        :show-after="500"
        :hide-after="200"
      >
        <div
          class="device-card"
          :class="{
            'device-busy': !isDeviceSelectable(device),
            'device-selected': selectedDevices.includes(device.device_id),
          }"
          @click.stop="
            toggleDevice(device.device_id, !isDeviceSelectable(device))
          "
        >
          <div
            class="device-icon"
            @click.stop="
              navigateToDeviceDetail(device.device_id, device.device_id)
            "
            title="打开设备控制"
          >
            <img
              src="@/assets/images/devices/device-icon.png"
              alt="设备图标"
              class="device-icon-image"
            />
          </div>
          <div class="device-info">
            <div class="device-name">{{ device.device_id || '未知设备' }}</div>
            <div class="device-model">
              型号: {{ device.model || 'undefined' }}
            </div>
          </div>
          <div class="device-status">
            <el-tag :type="getDeviceStatusType(device)" size="small">
              {{ getDeviceStatusText(device) }}
            </el-tag>
            <!-- 任务应用简称显示 -->
            <div
              v-if="
                device.is_busy &&
                device.task_description &&
                getAppShortNameFromTask(device.task_description)
              "
              class="device-task-app"
            >
              {{ getAppShortNameFromTask(device.task_description) }}
            </div>
          </div>
        </div>
      </el-tooltip>

      <div
        v-if="filteredDevices.length === 0 && !devicesLoading"
        class="empty-state"
      >
        <div class="empty-text">暂无设备</div>
      </div>
    </div>

    <!-- 设备分页 -->
    <div class="pagination-section">
      <div class="pagination-wrapper">
        <div class="page-size-selector">
          <span class="page-size-label">每页显示</span>
          <el-select
            v-model="pageSize"
            @change="handleSizeChange"
            size="default"
            style="width: 80px; margin: 0 8px"
          >
            <el-option
              v-for="size in [10, 20, 50, 100]"
              :key="size"
              :label="size"
              :value="size"
            />
          </el-select>
          <span class="page-size-label">条</span>
        </div>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :small="false"
          :disabled="false"
          :background="true"
          layout="prev, pager, next, jumper"
          :total="filteredDevicesAll.length"
          :pager-count="7"
          :hide-on-single-page="false"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 应用工具栏 -->
    <div class="app-toolbar">
      <div class="left-section">
        <h3>选择应用</h3>
      </div>

      <div class="app-right-section">
        <el-input
          v-model="appSearchKeyword"
          placeholder="搜索应用..."
          clearable
          class="app-search-input"
          @input="handleAppSearch"
        >
          <template #prefix>
            <SvgIcon name="search" size="16px" />
          </template>
        </el-input>

        <el-button
          type="primary"
          size="default"
          @click="loadDeviceApps"
          :loading="appsLoading"
          plain
        >
          <SvgIcon name="reload" size="18px" />
          <span style="margin-left: 6px">刷新</span>
        </el-button>
      </div>
    </div>

    <!-- 应用区域 -->
    <div>
      <!-- 应用列表 -->
      <div
        v-if="availableApps.length > 0 && !appsLoading"
        class="app-cards-grid"
      >
        <el-tooltip
          :content="`${app.package_name} (${app.package})`"
          placement="top"
          :disabled="!app.package_name || app.package_name.length <= 15"
          v-for="app in filteredApps"
          :key="app.package"
        >
          <div
            class="app-card"
            :class="{ 'app-selected': selectedApp === app.package }"
            @click="selectApp(app.package)"
          >
            <div class="app-card-icon">
              <img
                v-if="getAppIconImage(app.package)"
                :src="getAppIconImage(app.package)"
                :alt="app.package_name"
                class="app-icon-image"
              />
              <SvgIcon v-else name="apps" size="24px" />
            </div>
            <div class="app-card-info">
              <div class="app-card-name">{{ app.package_name }}</div>
              <div class="app-card-package">{{ app.package }}</div>
            </div>
            <div class="app-card-actions">
              <el-tag
                v-if="selectedApp === app.package"
                type="success"
                size="small"
              >
                已选择
              </el-tag>
            </div>
          </div>
        </el-tooltip>
      </div>

      <!-- 应用加载状态 -->
      <div
        v-else-if="appsLoading"
        class="app-cards-grid"
        v-loading="appsLoading"
        style="min-height: 128px"
      ></div>
    </div>

    <!-- 测试配置区域 -->
    <div class="test-config-area">
      <h3>测试配置</h3>
      <div class="config-form">
        <el-form :model="testConfig" label-width="100px" size="default">
          <el-form-item label="测试时长">
            <el-input-number
              v-model="testConfig.testTime"
              :min="1"
              :step="1"
              size="default"
              style="width: 120px; z-index: 0"
              @change="handleTestTimeChange"
            />
            <span style="margin-left: 8px; color: #606266">分钟</span>
            <el-radio-group
              v-model="is_prod"
              size="small"
              style="margin-left: 20px"
            >
              <el-radio-button label="prod" value="1" />
              <el-radio-button label="test" value="2" />
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 测试执行按钮 -->
    <div class="test-execute-section">
      <div class="test-summary-info">
        <el-alert
          :title="`将在 ${
            selectedDevices.length
          } 台设备上测试应用: ${getSelectedAppName()}`"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
      <div class="test-execute-actions">
        <el-tooltip
          :content="getTestButtonTooltip"
          placement="top"
          :disabled="canStartTest"
        >
          <el-button
            type="primary"
            size="large"
            :disabled="!canStartTest"
            :loading="testing"
            @click="checkDdevicePhone"
          >
            {{
              testing
                ? '正在启动测试，请稍候...'
                : `开始Monkey测试 (${selectedDevices.length} 台设备)`
            }}
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 测试面板 -->
    <el-drawer
      v-model="showTestPanel"
      title="批量测试配置"
      size="50%"
      direction="rtl"
    >
      <div class="test-panel">
        <div class="selected-devices">
          <h3>选择的设备 ({{ selectedDevices.length }})</h3>
          <div class="device-list">
            <div
              v-for="deviceId in selectedDevices"
              :key="deviceId"
              class="device-item"
            >
              <img
                src="@/assets/images/devices/device-icon.png"
                alt="设备图标"
                class="device-item-icon"
              />
              <span>{{ getDeviceName(deviceId) }}</span>
            </div>
          </div>
        </div>

        <div class="app-selection">
          <h3>选择测试应用</h3>
          <el-select
            v-model="selectedApp"
            placeholder="请选择要测试的应用"
            filterable
            size="default"
            style="width: 100%"
            @change="handleAppChange"
          >
            <el-option
              v-for="app in availableApps"
              :key="app.package"
              :label="`${app.package_name}`"
              :value="app.package"
            >
              <div class="app-option">
                <img
                  v-if="getAppIconImage(app.package)"
                  :src="getAppIconImage(app.package)"
                  :alt="app.package_name"
                  class="app-option-icon"
                />
                <div class="app-option-info">
                  <div class="app-option-name">{{ app.package_name }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </div>
      </div>
    </el-drawer>

    <!-- 测试进度弹窗 -->
    <el-dialog
      v-model="showTestDialog"
      title="测试进度"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="test-progress">
        <div class="progress-summary">
          <el-progress
            :percentage="testProgress"
            :status="testStatus"
            :stroke-width="8"
          />
          <div class="progress-text">
            {{ testProgressText }}
          </div>
        </div>

        <div class="device-progress-list">
          <div
            v-for="result in testResults"
            :key="result.deviceId"
            class="device-progress-item"
          >
            <div class="device-name">{{ getDeviceName(result.deviceId) }}</div>
            <div class="device-status">
              <el-tag
                :type="
                  result.status === 'success'
                    ? 'success'
                    : result.status === 'running'
                    ? 'warning'
                    : 'danger'
                "
                size="small"
              >
                {{ getTestStatusText(result.status) }}
              </el-tag>
              <span class="test-time" v-if="result.reportId">
                报告ID: {{ result.reportId }}
              </span>
            </div>
            <div v-if="result.message" class="result-message">
              {{ result.message }}
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeTestDialog" :disabled="testing">
          {{ testing ? '测试中...' : '关闭' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 设备控制弹窗 -->
    <!-- <div class="device-control-modal" v-if="showDeviceControlModal">
      <div class="modal-overlay" @click="closeDeviceControlModal"></div>
      <div class="modal-container">
        <div class="modal-header">
          <h3>设备控制 - {{ currentDeviceName }}</h3>
          <div class="header-actions">
            <button
              class="refresh-btn-modal"
              @click="refreshIframe"
              title="刷新"
            >
              刷新
            </button>
            <span
              class="close-btn"
              @click="closeDeviceControlModal"
              title="关闭"
            >
              &times;
            </span>
          </div>
        </div>
        <div class="modal-body">
          <iframe
            :src="currentDeviceUrl"
            frameborder="0"
            class="device-control-frame"
            ref="deviceControlFrame"
          ></iframe>
        </div>
      </div>
    </div> -->
  </div>
  <el-dialog
    v-for="device in filteredDevices"
    :key="device.device_id"
    v-model="dialogStates[device.device_id]"
    draggable
    center
    :modal="false"
    :close-on-click-modal="false"
    style="pointer-events: auto"
    :id="device.device_id"
    :destroy-on-close="true"
    @close="closeDeviceControlModal(device.device_id)"
    :show-close="false"
    :fullscreen="false"
    :width="kuan"
    :style="{
      height: chang + 'px',
      marginTop: '10px',
      zIndex: 2000 + first_z_index,
    }"
    class="app-device-control-dialog"
    @open="handleDialogOpen"
  >
    <template #header="{ titleId, titleClass }">
      <div>
        <h4 :id="titleId" :class="titleClass">设备：{{ device.device_id }}</h4>
      </div>
    </template>
    <div class="modal-header" style="margin-top: 10px">
      <!-- <h3>设备：{{ device.device_id }}</h3> -->
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="refreshIframe(device.device_id)"
        >
          刷新
        </el-button>
        <el-button
          type="primary"
          size="small"
          @click="hengPing(device.device_id)"
        >
          {{ hengPingText }}
        </el-button>
      </div>
      <el-button
        type="danger"
        size="small"
        @click="closeDeviceControlModal(device.device_id)"
      >
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
      </el-button>
    </div>

    <iframe
      :src="deviceControlFrames[device.device_id]"
      frameborder="0"
      class="device-control-frame"
      :ref="(el) => setIframeRef(el, device.device_id)"
      :style="{ width: kuan - 20 + 'px' }"
    ></iframe>
  </el-dialog>
  <el-dialog v-model="device_phone_status" title="设备账号">
    <el-table :data="device_phone_data" style="width: 100%">
      <el-table-column prop="device_id" label="设备(支持lit)" width="280" />
      <el-table-column prop="phone" label="登录账号" width="180">
        <template #default="scope">
          <div v-if="scope.row.editMode">
            <el-input
              v-model="scope.row.phone"
              ref="inputRef"
              @blur="confirmEdit(scope.row)"
              @keyup.enter="confirmEdit(scope.row)"
            />
          </div>
          <span
            v-else
            @click="startEdit(scope.row, scope.$index)"
            style="min-height: 3px; min-width: 3px"
          >
            {{ scope.row.phone }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="登录状态" width="180" />
    </el-table>
    <template #header="{}">
      <el-radio-group v-model="radio" size="small">
        <!-- <el-radio-button label="airtest登录" value="1" /> -->
        <el-radio-button label="uiautomator2登录" value="2" />
      </el-radio-group>
      <el-radio-group v-model="is_login" size="small">
        <el-radio-button label="手动登录" value="1" />
        <el-radio-button label="自动登录" value="2" />
      </el-radio-group>
    </template>
    <div style="margin-left: 60%; margin-top: 10px">
      <el-button type="primary" plain size="default" @click="closeCheck">
        取消
      </el-button>
      <el-button type="primary" plain size="default" @click="bath_login">
        仅执行登录
      </el-button>

      <el-button type="primary" plain size="default" @click="handleStartTest">
        执行monkey
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'DeviceAppViewV2',
}
</script>

<script  setup>
import { ref, computed, onMounted, nextTick, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import SvgIcon from '@/views/components/SvgIcon.vue'
import emmit from '@/utils/emitter'
import { CircleCloseFilled } from '@element-plus/icons-vue'
defineOptions({
  name: 'DeviceAppV2',
})
// TODO 图片加载
const images = import.meta.glob('@/assets/images/packages/*.png', {
  eager: true,
})
const images_packages = (path) => {
  return images[path.replace('@/assets', '/src/assets')].default
}
let kuan = ref(450)
let chang = ref(860)
let hengPingStatus = ref(false)
let hengPingText = ref('横屏')
const hengPing = (device_id) => {
  hengPingStatus.value = !hengPingStatus.value
  if (hengPingStatus.value) {
    kuan.value = 860
    hengPingText.value = '竖屏'
  } else {
    kuan.value = 450
    hengPingText.value = '横屏'
  }
  refreshIframe(device_id)
}
const dialogStates = reactive({})
const deviceControlFrames = reactive({})
// 响应式数据
const devicesLoading = ref(false)
const appsLoading = ref(false)
const testing = ref(false)
const showTestDialog = ref(false)
const showTestPanel = ref(false)

// 设备控制相关数据
const showDeviceControlModal = ref(false)
const currentDeviceName = ref('')
const currentDeviceUrl = ref('')
const deviceControlFrame = ref(null)

const availableDevices = ref([])
const selectedDevices = ref([])
const availableApps = ref([])
const selectedApp = ref('')
const testResults = ref([])
const testProgress = ref(0)
const testStatus = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

// 搜索和筛选功能
const searchKeyword = ref('')
const deviceFilter = ref('all')
const appSearchKeyword = ref('')

// 测试配置
const testConfig = ref({
  testTime: getLastTestTime(), // 获取上次的测试时长，默认10分钟
})

// 获取上次的测试时长
function getLastTestTime() {
  const lastTestTime = localStorage.getItem('fastbot_last_test_time')
  return lastTestTime ? parseInt(lastTestTime) : 10 // 默认10分钟
}

// 保存测试时长到本地存储
function saveTestTime(time) {
  localStorage.setItem('fastbot_last_test_time', time.toString())
}

// 处理测试时长变化
const handleTestTimeChange = (value) => {
  if (value && value > 0) {
    saveTestTime(value)
  }
}

// 计算属性
const filteredDevicesAll = computed(() => {
  let filtered = availableDevices.value

  // 搜索过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(
      (device) =>
        device.device_id &&
        device.device_id
          .toLowerCase()
          .includes(searchKeyword.value.toLowerCase()),
    )
  }

  // 状态过滤
  if (deviceFilter.value === 'available') {
    filtered = filtered.filter((device) => isDeviceSelectable(device))
  } else if (deviceFilter.value === 'busy') {
    filtered = filtered.filter(
      (device) =>
        device.is_busy &&
        (device.task_type === 'testing' || device.task_type === 'installing'),
    )
  }

  return filtered
})

const filteredDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDevicesAll.value.slice(start, end)
})

const canStartTest = computed(() => {
  return (
    selectedDevices.value.length > 0 &&
    selectedApp.value &&
    !testing.value &&
    !isSelectedDevicesBusy.value
  )
})

// 检查选中的设备是否有忙碌的
const isSelectedDevicesBusy = computed(() => {
  return selectedDevices.value.some((deviceId) => {
    const device = availableDevices.value.find((d) => d.device_id === deviceId)
    return device && device.is_busy
  })
})

// 获取测试按钮状态提示
const getTestButtonTooltip = computed(() => {
  if (selectedDevices.value.length === 0) {
    return '请先选择设备'
  }
  if (!selectedApp.value) {
    return '请先选择应用'
  }
  if (testing.value) {
    return '测试正在进行中'
  }
  if (isSelectedDevicesBusy.value) {
    return '选中的设备中有设备正在忙碌'
  }
  return '点击开始测试'
})

const availableCount = computed(() => {
  return availableDevices.value.filter((device) => isDeviceSelectable(device))
    .length
})

const busyCount = computed(() => {
  return availableDevices.value.filter(
    (device) =>
      device.is_busy &&
      (device.task_type === 'testing' || device.task_type === 'installing'),
  ).length
})

const testProgressText = computed(() => {
  const totalDevices = testResults.value.length
  const completedTests = testResults.value.filter(
    (r) => r.status === 'success' || r.status === 'failed',
  ).length
  return `测试进度：${completedTests}/${totalDevices} 台设备完成`
})

const filteredApps = computed(() => {
  let apps = availableApps.value

  // 搜索过滤
  if (appSearchKeyword.value) {
    apps = apps.filter(
      (app) =>
        (app.package_name &&
          app.package_name
            .toLowerCase()
            .includes(appSearchKeyword.value.toLowerCase())) ||
        (app.package &&
          app.package
            .toLowerCase()
            .includes(appSearchKeyword.value.toLowerCase())),
    )
  }

  return apps
})

// 应用图标映射
const appIconMap = {
  'com.litatom.app': images_packages('@/assets/images/packages/Litmatch.png'),
  'com.ofotech.app': images_packages('@/assets/images/packages/Ofo.png'),
  'com.ofotech.inparty': images_packages(
    '@/assets/images/packages/InParty.png',
  ),
  'com.ofotech.app.in': images_packages('@/assets/images/packages/Deer.png'),
  'com.nimispace.app': images_packages('@/assets/images/packages/NIMI.png'),
}

// 方法
const getAppIconImage = (packageName) => {
  if (!packageName) return null

  // 检查精确匹配
  if (appIconMap[packageName]) {
    return appIconMap[packageName]
  }

  // 检查包含关系
  const lowerPackage = packageName.toLowerCase()
  if (lowerPackage.includes('litmatch') || lowerPackage.includes('litatom')) {
    return images_packages('@/assets/images/packages/Litmatch.png')
  }
  if (
    lowerPackage.includes('ofotech.app') &&
    !lowerPackage.includes('inparty') &&
    !lowerPackage.includes('.in')
  ) {
    return images_packages('@/assets/images/packages/Ofo.png')
  }
  if (lowerPackage.includes('inparty')) {
    return images_packages('@/assets/images/packages/InParty.png')
  }
  if (
    lowerPackage.includes('ofotech.app.in') ||
    lowerPackage.includes('deer')
  ) {
    return images_packages('@/assets/images/packages/Deer.png')
  }
  if (lowerPackage.includes('nimi')) {
    return images_packages('@/assets/images/packages/NIMI.png')
  }

  return images_packages('@/assets/images/packages/default-app-icon.png')
}

const getDeviceStatusType = (device) => {
  if (device.is_busy) return 'warning'
  return 'success'
}

const getDeviceStatusText = (device) => {
  if (device.is_busy) {
    // 根据任务类型显示更详细的状态
    if (device.task_type === 'testing') return '测试中'
    if (device.task_type === 'installing') return '安装中'
    return '忙碌中'
  }
  return '空闲'
}

const isDeviceSelectable = (device) => {
  // 只有空闲状态的设备才能选择
  return !device.is_busy
}

const shouldShowDeviceTooltip = (device) => {
  // 安装中或测试中状态需要显示气泡
  return (
    device.is_busy &&
    (device.task_type === 'testing' || device.task_type === 'installing')
  )
}

const getDeviceTooltipContent = (device) => {
  if (!shouldShowDeviceTooltip(device)) return ''

  let content = []
  if (device.task_description) {
    content.push(`任务：${device.task_description}`)
  }
  if (device.task_estimated_end_time) {
    content.push(`预计结束：${device.task_estimated_end_time}`)
  }
  return content.join('\n')
}

// 从task_description中提取包名并转换为对应的简称
const getAppShortNameFromTask = (taskDescription) => {
  if (!taskDescription) return ''

  // 包名到简称的映射
  const packageNameMap = {
    'com.litatom.app': 'Lit',
    'com.ofotech.app': 'Ofo',
    'com.ofotech.inparty': 'InParty',
    'com.ofotech.app.in': 'Deer',
    'com.nimispace.app': 'NiMi',
  }

  // 按照包名长度从长到短排序，确保精确匹配
  const sortedPackages = Object.keys(packageNameMap).sort(
    (a, b) => b.length - a.length,
  )

  // 在描述中查找包名
  for (const packageName of sortedPackages) {
    if (taskDescription.includes(packageName)) {
      return packageNameMap[packageName]
    }
  }

  // 如果没有找到匹配的包名，返回空字符串
  return ''
}

const getDeviceName = (deviceId) => {
  const device = availableDevices.value.find((d) => d.device_id === deviceId)
  return device?.device_name || deviceId
}

const getSelectedAppName = () => {
  if (!selectedApp.value) return ''
  const app = availableApps.value.find((a) => a.package === selectedApp.value)
  return app?.package_name || selectedApp.value
}

const getTestStatusText = (status) => {
  switch (status) {
    case 'running':
      return '测试中'
    case 'success':
      return '测试完成'
    case 'failed':
      return '测试失败'
    default:
      return '未知状态'
  }
}

const toggleDevice = async (deviceId, disabled) => {
  if (disabled) {
    try {
      await ElMessageBox.confirm('是否要停止任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      // 调用后端停止任务接口
      try {
        const res = await request.post(
          `/devices/network/device/${encodeURIComponent(deviceId)}/stop`,
        )
        if (res && (res.success || res.code === 200)) {
          ElMessage.success('已发送停止任务指令')
          // 停止后刷新设备列表，更新状态
          await refreshDevices()
        } else {
          ElMessage.error(res?.message || '停止任务失败')
        }
      } catch (e) {
        ElMessage.error('停止任务失败')
      }
    } catch (error) {
      // 用户取消，无需处理
    }
    return
  }

  const index = selectedDevices.value.indexOf(deviceId)
  if (index > -1) {
    selectedDevices.value.splice(index, 1)
  } else {
    selectedDevices.value.push(deviceId)
  }
}

const handleDeviceSearch = () => {
  currentPage.value = 1
}

const setDeviceFilter = (filter) => {
  deviceFilter.value = filter
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const handleAppChange = () => {
  // 应用改变时的处理逻辑
}

const selectApp = (packageName) => {
  selectedApp.value = packageName
  handleAppChange()
}

const handleAppSearch = () => {
  // 应用搜索逻辑处理
}
emmit.on('app_info', (data) => {
  // console.log(data)
  // console.log(data.app_info)
  // console.log(data.app_install)
  availableDevices.value = data.app_info.devices_info || []
  // // 初始化对话框状态
  // availableDevices.value.forEach((device) => {
  //   dialogStates[device.device_id] = false
  // })
})
const refreshDevices = async () => {
  devicesLoading.value = true

  try {
    const response = await request.get('/devices/info')
    if (response.success) {
      availableDevices.value = response.data.devices_info || []
      // 初始化对话框状态
      availableDevices.value.forEach((device) => {
        dialogStates[device.device_id] = false
      })
    } else {
      ElMessage.error(response.message || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    devicesLoading.value = false
  }
}

const loadDeviceApps = async () => {
  appsLoading.value = true
  try {
    // 获取应用包列表
    const response = await request.get('/devices/package_list')
    if (response.success) {
      availableApps.value = response.data.packages || []
    } else {
      ElMessage.error(response.message || '获取应用列表失败')
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    ElMessage.error('获取应用列表失败')
  } finally {
    appsLoading.value = false
  }
}

// 立即更新设备状态的方法
const updateDeviceStatus = (
  deviceIds,
  status,
  taskType = null,
  taskDescription = null,
) => {
  if (!Array.isArray(deviceIds)) {
    deviceIds = [deviceIds]
  }

  availableDevices.value = availableDevices.value.map((device) => {
    if (deviceIds.includes(device.device_id)) {
      return {
        ...device,
        is_busy: status === 'idle' ? false : true,
        current_status: status,
        task_type: taskType,
        task_description: taskDescription,
        task_start_time:
          status !== 'idle' ? new Date().toLocaleString('zh-CN') : null,
        task_estimated_duration:
          status === 'testing' ? testConfig.value.testTime * 60 : null,
      }
    }
    return device
  })
}
let login_id = []
let login_phone = {}
emmit.on('login_res', (data) => {
  login_id.push(data.device_id)
  login_phone[data.device_id] = data.phone
})
// 设备启动
let radio = ref('2')
let is_prod = ref('2')
let is_login = ref('2')
let device_phone_status = ref(false)
let device_phone_data = ref([])
let phone_list
const checkDdevicePhone = () => {
  // 使用 axios 发起 GET 请求(推荐)
  request
    .get('/fastbot/get_phone', {
      params: { is_prod: is_prod.value, app_name: selectedApp.value }, // 查询参数
    })
    .then((response) => {
      console.log(response.data)
      phone_list = response.data
      device_phone_data.value = []
      for (let index = 0; index < selectedDevices.value.length; index++) {
        const element = selectedDevices.value[index]
        device_phone_data.value.push({
          device_id: element,
          phone: index < phone_list.length ? phone_list[index] : '',
          status:
            login_id.indexOf(element) > -1 ? `✅${login_phone[element]}` : '❌',
        })
      }
      device_phone_status.value = true
    })
    .catch((error) => {
      console.error(error)
    })
}
const closeCheck = () => {
  device_phone_status.value = false
}
let inputRef = ref()
let editIndex = ref(-1)
function startEdit(row, index) {
  //   if (editIndex.value !== -1) {
  //     // 如果已经有正在编辑的行，先保存
  //     console.log(11111111)
  //     confirmEdit(tableData[editIndex.value])
  //   }
  row.editMode = true
  editIndex.value = index
  nextTick(() => {
    inputRef?.value.focus()
  })
}
function confirmEdit(row) {
  console.log(row.phone)
  if (row.phone) {
    row.editMode = false
    editIndex.value = -1
  }
}
const bath_login = async () => {
  ElMessage.success('开始登录')
  const response = await request.post('/fastbot/batch_login', {
    device_ids: selectedDevices.value,
    package_name: selectedApp.value,
    device_phone_data: device_phone_data.value,
    type: radio.value,
  })

  if (response.success) {
    console.log(111)
    ElMessage.success(response.message)
  }
  device_phone_status.value = false
}
const handleStartTest = async () => {
  if (!canStartTest.value) return
  device_phone_status.value = false
  testing.value = true
  showTestDialog.value = true
  testProgress.value = 0
  testStatus.value = ''
  testResults.value = []

  // 保存测试时长到本地存储
  saveTestTime(testConfig.value.testTime)

  // 立即更新设备状态为测试中
  updateDeviceStatus(
    selectedDevices.value,
    'testing',
    'testing',
    `Fastbot测试: ${getSelectedAppName()}`,
  )

  try {
    const response = await request.post('/fastbot/v1/batch_start', {
      device_ids: selectedDevices.value,
      package_name: selectedApp.value,
      test_time: testConfig.value.testTime,
      device_phone_data: device_phone_data.value,
      type: radio.value,
      is_login: is_login.value == '2' ? true : false,
    })

    if (response.success) {
      testResults.value = response.data.devices_info.map((info) => ({
        deviceId: info.device_id,
        status: info.status,
        reportId: info.report_id,
        message: '测试启动成功',
      }))

      testProgress.value = 100
      testStatus.value = 'success'
      ElMessage.success('批量测试启动成功')

      // 关闭测试面板
      showTestPanel.value = false

      // 清空选中的设备和应用
      selectedDevices.value = []
      selectedApp.value = ''

      // 刷新设备列表（获取真实状态）
      await refreshDevices()
    } else {
      ElMessage.error(response.message || '测试启动失败')
      testStatus.value = 'exception'

      // 测试启动失败时重置设备状态
      updateDeviceStatus(selectedDevices.value, 'idle')

      // 测试启动失败时也清空选中状态
      selectedDevices.value = []
      selectedApp.value = ''
    }
  } catch (error) {
    console.error('测试启动失败:', error)
    ElMessage.error('测试启动失败')
    testStatus.value = 'exception'

    // 测试启动失败时重置设备状态
    updateDeviceStatus(selectedDevices.value, 'idle')

    // 测试启动失败时也清空选中状态
    selectedDevices.value = []
    selectedApp.value = ''
  } finally {
    testing.value = false
  }
}

const closeTestDialog = () => {
  showTestDialog.value = false
  testResults.value = []
  testProgress.value = 0
}
//新开设备在最上层
let first_z_index = ref(1)
const handleDialogOpen = () => {
  console.log(first_z_index.value)
  first_z_index.value = first_z_index.value + 1
}
// 打开设备控制相关方法
const navigateToDeviceDetail = (deviceId, deviceName) => {
  // 使用协议自适应的设备控制配置
  const deviceControlConfig = window.getDeviceControlConfig('auto')

  const encodedUdid = encodeURIComponent(`${deviceName}`)
  const wsUrl = encodeURIComponent(
    `${deviceControlConfig.wsProtocol}://${deviceControlConfig.wsServer}/?action=proxy-adb&remote=tcp%3A8886&udid=${deviceName}`,
  )
  const url = `${deviceControlConfig.baseUrl}#!action=stream&udid=${encodedUdid}&player=mse&ws=${wsUrl}`

  console.log('设备控制URL（协议自适应）:', {
    currentProtocol: window.location.protocol,
    baseUrl: deviceControlConfig.baseUrl,
    wsProtocol: deviceControlConfig.wsProtocol,
    finalUrl: url,
  })

  currentDeviceName.value = deviceName
  // currentDeviceUrl.value = url
  deviceControlFrames[deviceName] = url
  dialogStates[deviceName] = true
  // showDeviceControlModal.value = true
  document.body.style.overflow = 'hidden'
  //elementplus实现dialog遮罩层外的元素可以被操作点击
  nextTick(() => {
    // 把弹窗父亲的父亲 dom 元素添加 pointer-events: none; 防止穿透
    const elDialog = document.getElementById(deviceName)
    // @ts-ignore
    elDialog?.parentNode?.parentNode?.setAttribute(
      'style',
      'pointer-events: none;',
    )
  })
}

const closeDeviceControlModal = (value) => {
  showDeviceControlModal.value = false
  dialogStates[value] = false
  currentDeviceUrl.value = ''
  deviceControlFrames[value] = ''
  document.body.style.overflow = 'auto'
}
// 使用对象存储 refs
const iframeRefs = ref({})

const setIframeRef = (el, id) => {
  iframeRefs.value[id] = el
}
const refreshIframe = (deviceId) => {
  const iframe = iframeRefs.value[deviceId]

  if (iframe) {
    const currentSrc = iframe.src
    iframe.src = ''
    setTimeout(() => {
      iframe.src = currentSrc
      ElMessage.info('正在刷新设备控制页面...')
    }, 50)
  }
}

// 生命周期钩子
onMounted(() => {
  refreshDevices()
  loadDeviceApps()
})
</script>
  <style lang="scss">
.app-device-control-dialog .el-dialog__body {
  height: 780px;
}
.app-device-control-dialog .el-dialog__header {
  height: 10px !important;
  padding: 0 !important;
}
</style>
<style scoped lang='scss'>
.el-overlay-dialog {
  z-index: 1;
}
.device-app-container {
  padding: 20px;
  max-width: 100%;
  margin: 0;
  width: 100%;
  /* background: #ffffff; */
  min-height: calc(100vh - 74px);
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 8px;
}

.page-header h3 {
  margin: 0;
  /* color: #606266; */
  font-size: 22px;
  font-weight: 600;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.left-section h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #606266;
}

.device-summary {
  padding: 2px 8px;
  /* background: #f0f7ff; */
  border-radius: 4px;
  border: 1px solid #d0e7ff;
}

.summary-text {
  color: #409eff;
  font-size: 12px;
  font-weight: 500;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.search-input {
  width: 280px;
}

.filter-buttons {
  flex-shrink: 0;
}

.filter-buttons .el-button {
  font-size: 12px;
  padding: 8px 12px;
}

/* 设备统计样式 */
.device-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  padding: 10px 14px;
  /* background: white; */
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
  height: 42px;
}

.stat-item {
  color: #606266;
  font-size: 14px;
}

.stat-number {
  font-weight: 600;
  margin-left: 4px;
}

.stat-number.idle {
  color: #67c23a;
}

.stat-number.busy {
  color: #e6a23c;
}

.stat-number.total {
  color: #409eff;
}

.selected-info {
  margin-left: auto;
  height: 32px;
  display: flex;
  align-items: center;
  flex-shrink: 0;
  overflow: hidden;
}

.selected-info .el-button {
  height: 28px;
  line-height: 26px;
  padding: 0 12px;
  font-size: 12px;
}

/* 设备网格样式 */
.device-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 8px;
  margin-bottom: 8px;
  max-height: 264px;
  min-height: 60px;
  overflow-y: auto;
}

.device-card {
  /* background: white; */
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 60px;
  max-width: 280px;
}

.device-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.device-card.device-selected {
  border-color: #409eff;
  background: #f0f7ff;
}

.device-card.device-busy {
  opacity: 0.6;
  cursor: pointer; /* 忙碌也允许点击，触发停止任务确认 */
  background: #f5f5f5;
}

.device-card.device-busy:hover {
  border-color: var(--el-border-color);
  box-shadow: none;
}

.device-icon {
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  flex-shrink: 0;
}

.device-icon-image {
  width: 34px;
  height: 34px;
  object-fit: contain;
}

.device-info {
  flex: 1;
  min-width: 0;
  max-width: 150px;
}

.device-name {
  font-weight: 600;
  color: #606266;
  font-size: 13px;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.device-model {
  color: #606266;
  font-size: 11px;
  margin-bottom: 0;
  line-height: 1.2;
}

.device-status {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.device-status .el-tag {
  font-size: 10px;
  padding: 2px 6px;
  height: auto;
  line-height: 1.2;
}

.device-task-app {
  font-size: 10px;
  color: #409eff;
  font-weight: 600;
  text-align: center;
  padding: 2px 2px;
  background: #ecf5ff;
  border-radius: 3px;
  border: 1px solid #b3d8ff;
  min-width: 28px;
  box-shadow: 0 1px 2px rgba(64, 158, 255, 0.1);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60px;
  grid-column: 1 / -1;
  width: 100%;
}

.empty-text {
  color: #606266;
  font-size: 14px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-start;
  margin: 4px 0;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
  width: 100%;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.page-size-selector :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
  height: 32px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper :deep(.el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  border-radius: 6px;
  margin: 0 2px;
  font-weight: 500;
  border: 1px solid #dcdfe6;
  /* background: white; */
  color: #606266;
}

.pagination-wrapper :deep(.el-pager li:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.el-pager li.is-active) {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev),
.pagination-wrapper :deep(.btn-next) {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
  font-weight: 500;
}

.pagination-wrapper :deep(.btn-prev:hover),
.pagination-wrapper :deep(.btn-next:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev:disabled),
.pagination-wrapper :deep(.btn-next:disabled) {
  /* color: #c0c4cc; */
  /* background-color: #fff; */
  border-color: var(--el-border-color);
  cursor: not-allowed;
}

/* 应用选择区域样式 */
.app-selection-area {
  margin-top: 12px;
}

.app-selection-area h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
}

.app-selection-content {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.app-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.app-option-icon {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  object-fit: contain;
}

.app-option-info {
  flex: 1;
}

.app-option-name {
  font-size: 14px;
  color: #606266;
  line-height: 1.2;
}

.app-option-package {
  font-size: 12px;
  color: #606266;
  line-height: 1.2;
}

/* 测试配置区域样式 */
.test-config-area {
  margin-top: 12px;
}

.test-config-area h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
}

/* 测试执行区域样式 */
.test-execute-section {
  margin-top: 12px;
}

.test-summary-info {
  margin-bottom: 16px;
}

.test-execute-actions {
  text-align: center;
}

/* 测试面板样式 */
.test-panel {
  padding: 20px;
}

.selected-devices {
  margin-bottom: 24px;
}

.selected-devices h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
}

.device-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.device-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #f0f7ff;
  border-radius: 4px;
  border: 1px solid #d0e7ff;
  color: #409eff;
  font-size: 12px;
}

.device-item-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.app-selection {
  margin-bottom: 24px;
}

.app-selection h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
}

.test-configuration {
  margin-bottom: 24px;
}

.test-configuration h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
}

.test-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color);
}

.test-tips {
  margin-bottom: 16px;
}

.test-alert {
  border-radius: 6px;
  text-align: left;
}

.operation-status {
  margin-top: 16px;
}

.status-alert {
  border-radius: 6px;
  text-align: left;
}

/* 测试进度样式 */
.test-progress {
  padding: 20px;
}

.progress-summary {
  margin-bottom: 24px;
  text-align: center;
}

.progress-text {
  margin-top: 12px;
  font-size: 14px;
  color: #606266;
}

.device-progress-list {
  max-height: 300px;
  overflow-y: auto;
}

.device-progress-item {
  padding: 12px 0;
  border-bottom: 1px solid #f5f7fa;
}

.device-progress-item:last-child {
  border-bottom: none;
}

.device-progress-item .device-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.device-progress-item .device-status {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.test-time {
  font-size: 12px;
  color: #606266;
}

.result-message {
  font-size: 12px;
  color: #606266;
}

/* 应用工具栏样式 */
.app-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.app-left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.app-search-input {
  width: 300px;
}

.app-right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

/* 应用卡片网格样式 */
.app-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 8px;
  margin-bottom: 8px;
  max-height: 128px;
  overflow-y: auto;
}

.app-card {
  /* background: white; */
  border: 2px solid var(--el-border-color);
  border-radius: 6px;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 60px;
  max-width: 280px;
}

.app-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.app-card.app-selected {
  border-color: #409eff;
  background: #f0f7ff;
}

.app-card-icon {
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  flex-shrink: 0;
  background: #f8f9fa;
  border-radius: 6px;
}

.app-icon-image {
  width: 28px;
  height: 28px;
  object-fit: contain;
}

.app-card-info {
  flex: 1;
  min-width: 0;
  max-width: 150px;
}

.app-card-name {
  font-weight: 600;
  color: #606266;
  font-size: 13px;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

.app-card-package {
  color: #606266;
  font-size: 11px;
  margin-bottom: 0;
  line-height: 1.2;
}

.app-card-actions {
  flex-shrink: 0;
}

.app-card-actions .el-tag {
  font-size: 10px;
  padding: 2px 6px;
  height: auto;
  line-height: 1.2;
}

.app-empty-hint {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 16px 0;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  color: #606266;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .device-app-container {
    padding: 16px;
  }

  .page-header h3 {
    font-size: 20px;
  }

  .device-grid {
    grid-template-columns: 1fr;
    max-height: 300px;
  }

  .toolbar,
  .quick-test-section {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .left-section,
  .right-section {
    flex-direction: column;
    gap: 12px;
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .filter-buttons {
    display: flex !important;
    flex-wrap: wrap;
    gap: 4px;
  }

  .app-selection-content {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-wrapper {
    flex-direction: column;
    gap: 16px;
  }

  .page-size-selector {
    order: 2;
  }
}

@media (max-width: 1024px) {
  .device-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .filter-buttons .el-button {
    font-size: 11px;
    padding: 6px 10px;
  }
}

/* 设备控制弹窗样式 */
.device-control-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-container {
  position: relative;
  width: auto;
  max-width: 30%;
  height: 90vh;
  aspect-ratio: 0.486;
  /* background-color: #fff; */
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  z-index: 1;
  animation: modal-appear 0.3s ease-out;
  padding: 0;
}

@keyframes modal-appear {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  /* background-color: #f5f7fa; */
  border-bottom: 1px solid var(--el-border-color);
  min-height: 40px;
}

.modal-header h3 {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-btn-modal {
  display: inline-block;
  padding: 4px 8px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s;
}

.refresh-btn-modal:hover {
  background-color: #66b1ff;
}

.close-btn {
  font-size: 24px;
  color: #606266;
  cursor: pointer;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #606266;
}

.modal-body {
  flex: 1;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0;
}

.device-control-frame {
  width: 100%;
  height: 100%;
  border: none;
  transform-origin: right center;
}

.device-icon {
  cursor: pointer;
  transition: background-color 0.2s;
}

.device-icon:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 设备控制弹窗响应式样式 */
@media (max-width: 992px) {
  .modal-container {
    max-width: 50%;
    aspect-ratio: 0.486;
  }

  .device-control-frame {
    transform: scale(0.95);
  }
}

@media (max-width: 768px) {
  .modal-container {
    width: auto;
    max-width: 75%;
    height: 85vh;
    aspect-ratio: 0.486;
  }

  .device-control-frame {
    transform: scale(0.9);
  }
}
</style> 